package logic

import (
	"context"
	"errors"
	"goods_srv/models"
	"goods_srv/pkg"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *goods.UpdatePasswordRequest) (*goods.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	var u models.User
	u.Mobile = in.Mobile
	err = u.GetUser()
	if err != nil {
		logx.Error("查询用户失败")
		return nil, errors.New("查询用户失败")
	}
	if u.ID == 0 {
		logx.Error("当前账号未注册，不允许修改密码")
		return nil, errors.New("当前账号未注册，不允许修改密码")
	}

	if u.Password != pkg.Md5(in.OldPassword) {
		logx.Error("旧密码错误，禁止修改")
		return nil, errors.New("旧密码错误，禁止修改")
	}

	if in.NewPassword != in.AckPassword {
		logx.Error("两次密码不一致")
		return nil, errors.New("两次密码不一致")
	}

	err = u.UpdatePassword(pkg.Md5(in.NewPassword))
	if err != nil {
		logx.Error("修改密码失败")
		return nil, errors.New("修改密码失败")
	}

	return &goods.UpdatePasswordResponse{
		UserId: int64(u.ID),
	}, nil
}
